<template>
  <div class="venues">
    <div class="venues-header">
      <el-row>
        <el-col :span="1">
          <el-button
            type="primary"
            v-btnpermission="'btn-venusadd'"
            @click="addDialogVisible = true"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1">
          <!-- 导入 -->
          <el-upload
            class="upload"
            :multiple="false"
            :show-file-list="false"
            accept="csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            :http-request="toLead"
          >
            <template #trigger>
              <el-button v-btnpermission="'btn-venusload'" type="primary"
                >导入</el-button
              >
            </template>
          </el-upload>
        </el-col>
      </el-row>
      <el-card class="drug-head-contatiner-title2">
        <el-form :inline="true" :model="formSearch" class="demo-form-inline">
          <el-form-item label="开始时间">
            <el-date-picker
              v-model="formSearch.StartTime"
              type="datetime"
              placeholder="--请选择--"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="结束时间">
            <el-date-picker
              v-model="formSearch.EndTime"
              type="datetime"
              placeholder="--请选择--"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="活动名称">
            <el-select
              v-model="formSearch.ActivityCode"
              filterable
              placeholder="--选择--"
              @change="selectActivityChange"
            >
              <el-option
                v-for="item in activityOption"
                :key="item.Code"
                :label="item.Name"
                :value="item.Code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="所属城市">
            <el-tree-select
              v-model="formSearch.CityCode"
              :data="cityTreeOption"
              :props="defaultProps"
              :render-after-expand="false"
              node-key="Code"
              check-strictly
              filterable
              clearable
              @change="cs11"
            />
          </el-form-item>
          <el-form-item label="场馆">
            <el-select
              v-model="formSearch.Venues"
              placeholder="--请选择--"
              clearable
              filterable
            >
              <el-option
                v-for="item in venuesOption"
                :key="item.Code"
                :label="item.CHIDescription"
                :value="item.Code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="赛事名称" prop="Venues">
            <el-input v-model="formSearch.MatchName" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">搜索</el-button>
            <el-button @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <div class="venues-list">
      <el-row>
        <el-col>
          <!-- 角色列表 -->
          <el-table :data="venuesList" border stripe>
            <!-- 索引列 -->
            <el-table-column
              type="index"
              label="#"
              :index="indexMethod"
            ></el-table-column>
            <el-table-column
              prop="ActivityName"
              label="活动名称"
            ></el-table-column>
            <el-table-column prop="CityName" label="所属城市"></el-table-column>
            <el-table-column
              prop="VenuesName"
              label="场馆名称"
            ></el-table-column>
            <el-table-column
              prop="StartTime"
              label="开始时间"
              :formatter="timeFormat"
            ></el-table-column>
            <el-table-column
              prop="EndTime"
              label="结束时间"
              :formatter="timeFormat"
            ></el-table-column>
            <el-table-column prop="IsValid" label="是否有效">
              <template #default="scope">
                <el-switch
                  v-model="scope.row.IsEffective"
                  :active-value="1"
                  :inactive-value="0"
                  disabled
                />
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button
                  size="small"
                  type="primary"
                  v-btnpermission="'btn-venusupdate'"
                  :icon="Edit"
                  @click="showEditDialog(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  size="small"
                  type="danger"
                  v-btnpermission="'btn-venusdelete'"
                  @click="rowDelete(scope.row.Code)"
                  :icon="Delete"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12" :offset="8">
          <el-pagination
            background
            layout="total, prev, pager, next"
            v-model:total="formSearch.total"
            v-model:page-size="formSearch.pageSize"
            v-model:current-page="formSearch.page"
            @current-change="handleCurrentChange"
          />
        </el-col>
      </el-row>
      <el-dialog
        title="新增/修改"
        v-model="addDialogVisible"
        width="40%"
        @close="addDislogClosed"
      >
        <el-form
          :model="addDialogForm"
          :rules="scheduleFormRulesMixin.addFormRules"
          ref="addDialogRef"
          label-width="100px"
          inline
        >
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="所属活动" prop="ActivityCode">
                <el-select
                  v-model="addDialogForm.ActivityCode"
                  placeholder="--请选择--"
                  filterable
                  @change="selectActivityChangeAdd"
                >
                  <el-option
                    v-for="item in activityOption"
                    :key="item.Code"
                    :label="item.Name"
                    :value="item.Code"
                  />
                </el-select> </el-form-item
            ></el-col>
            <el-col :span="10">
              <el-form-item label="所属城市" prop="CityCode">
                <el-tree-select
                  v-model="addDialogForm.CityCode"
                  :data="cityTreeOption"
                  :props="defaultProps"
                  :render-after-expand="false"
                  node-key="Code"
                  check-strictly
                  filterable
                  @change="cs11Add"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="场馆" prop="VenuesCode">
                <el-select
                  v-model="addDialogForm.VenuesCode"
                  placeholder="--请选择--"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="item in venuesOptionAdd"
                    :key="item.Code"
                    :label="item.CHIDescription"
                    :value="item.Code"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="10">
              <el-form-item label="赛事名称" prop="MatchName">
                <el-input v-model="addDialogForm.MatchName" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="开始时间" prop="StartTime">
                <el-date-picker
                  v-model="addDialogForm.StartTime"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                /> </el-form-item
            ></el-col>
            <el-col :span="10">
              <el-form-item label="结束时间" prop="EndTime">
                <el-date-picker
                  v-model="addDialogForm.EndTime"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                /> </el-form-item
            ></el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="20">
              <el-form-item label="是否有效" prop="IsEffective">
                <el-checkbox
                  v-model="addDialogForm.IsEffective"
                  :true-label="1"
                  :false-label="0"
                /> </el-form-item
            ></el-col>
          </el-row>
        </el-form>
        <template v-slot:footer>
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addFormSubmit">确 定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { scheduleFormRulesMixin } from '@/utils/mixin.js';
import moment from 'moment';
import {
  getScheduleList,
  addSchedule,
  editSchedule,
  delSchedule,
  addScheduleList,
} from '@/network/schedule.js';
import { ref, reactive, onBeforeMount } from 'vue';
import {
  getActivityDic,
  getCityTree,
  getActivityVenues,
} from '@/network/dictionary.js';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Edit, Delete } from '@element-plus/icons-vue';
import { importExcel } from '@/utils/excel';
const venuesOption = ref([]); //搜索中的
let venuesArray = [];
const venuesOptionAdd = ref([]); //新增、修改中的
//分页索引
const indexMethod = (index) => {
  return index + (formSearch.page - 1) * formSearch.pageSize + 1;
};
//导入Excel表格
const toLead = (e) => {
  importExcel.methods.importExcel(e, (res) => {
    if (res.length > 0) {
      addScheduleList(res)
        .then(() => {
          ElMessage.success('导入成功');
          initDict();
          initData();
        })
        .catch((err) => {
          console.log(err);
          ElMessage.error('导入失败！');
        });
    } else {
      ElMessage.error('请选择文件');
    }
  });
};
const selectActivityChange = (val) => {
  venuesOption.value = venuesArray.filter((it) => it.ActivityCode == val);
};
const selectActivityChangeAdd = (val) => {
  console.info(val, '活动变化');
  addDialogForm.value.VenuesCode = null;
  let array2 = [];
  if (addDialogForm.value.CityCode) {
    array2 = venuesArray.filter((it) => it.CityCode == val);
  } else {
    array2 = venuesArray;
  }
  venuesOptionAdd.value = array2.filter((it) => it.ActivityCode == val);
};
const cs11 = async (val) => {
  let venuesArray2 = venuesArray;
  if (formSearch.ActivityCode) {
    venuesArray2 = venuesArray.filter(
      (it) => it.ActivityCode == formSearch.ActivityCode,
    );
  }
  if (val) {
    venuesOption.value = venuesArray2.filter((it) => it.CityCode == val);
  } else {
    venuesOption.value = venuesArray2;
  }
};
const cs11Add = async (val) => {
  console.info(val, '场馆变化');
  let venuesArray2 = venuesArray;
  if (addDialogForm.value.ActivityCode) {
    venuesArray2 = venuesArray.filter(
      (it) => it.ActivityCode == addDialogForm.value.ActivityCode,
    );
  }
  if (val) {
    venuesOptionAdd.value = venuesArray2.filter((it) => it.CityCode == val);
  } else {
    venuesOptionAdd.value = venuesArray2;
  }
};
// 搜索条件
const formSearch = reactive({
  ActivityCode: '',
  CityCode: '',
  EndTime: getInitTime(),
  StartTime: getInitTime(7),
  total: 0,
  page: 1,
  pageSize: 10,
  Venues: '',
  MatchName: '',
});
function timeFormat(row, column, v, i) {
  return moment(String(v)).format('YYYY-MM-DD hh:mm:ss');
}
function getInitTime(intday, hour) {
  let secodenpast = new Date().getTime() - (intday || 0) * 24 * 60 * 60 * 1000;
  var now = new Date(secodenpast);
  var year = now.getFullYear(); //得到年份
  var month = now.getMonth(); //得到月份
  var date = now.getDate(); //得到日期
  hour = hour || ' 00:00:00'; //默认时分秒 如果传给后台的格式为年月日时分秒，就需要加这个，如若不需要，此行可忽略
  month = month + 1;
  month = month.toString().padStart(2, '0');
  date = date.toString().padStart(2, '0');
  let x = `${year}-${month}-${date}${hour}`;
  return x;
}
//初始化
let venuesList = ref(null);
const initData = async () => {
  let params = {
    page: formSearch.page,
    pageSize: formSearch.pageSize,
    startTime: formSearch.StartTime,
    endTime: formSearch.EndTime,
    activityCode: formSearch.ActivityCode,
    cityCode: formSearch.CityCode,
    matchName: formSearch.MatchName,
    venues: formSearch.Venues,
  };

  await getScheduleList(params).then((res) => {
    venuesList.value = res.data;
    formSearch.total = res.total;
  });
};

//初始化字典
const activityOption = ref([]);
const cityTreeOption = ref([]);

const defaultProps = {
  children: 'Children',
  label: 'Name',
  value: 'Code',
};
const initDict = async () => {
  await getActivityDic().then((res) => {
    activityOption.value = res;
  });
  //获取城市
  await getCityTree().then((res) => {
    cityTreeOption.value = res;
  });
  await getActivityVenues().then((res) => {
    venuesOption.value = res;
    venuesOptionAdd.value = res;
    venuesArray = res;
  });
};
onBeforeMount(() => {
  initData();
  initDict();
});
//新增
const addDialogVisible = ref(false);
const addDialogRef = ref(null);
const addDialogForm = ref({
  Code: 0,
  VenuesCode: null,
  StartTime: null,
  EndTime: null,
  MatchName: '',
  IsEffective: 1,
  CityCode: null,
  ActivityCode: null,
});
const addFormSubmit = async () => {
  await addDialogRef.value.validate(async (valid) => {
    if (valid) {
      await addSchedule(addDialogForm.value)
        .then(() => {
          addDialogVisible.value = false;
          initData();
          initDict();
          ElMessage.success('新增成功');
        })
        .catch(() => {
          ElMessage.success('新增失败');
        });
    } else {
      ElMessage.error('请按要求填写');
      return false;
    }
  });
};
const addDislogClosed = () => {
  addDialogRef.value.resetFields();
  addDialogRef.value.clearValidate();
};
//编辑
const showEditDialog = (row) => {
  addDialogVisible.value = true;
  addDialogForm.value = { ...row };
};
//删除
const rowDelete = async (id) => {
  await ElMessageBox.confirm('确定删除该条记录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async (action) => {
    if (action === 'confirm') {
      await delSchedule({ code: id })
        .then(() => {
          initData();
          // initDict();
          ElMessage.success('删除成功');
        })
        .catch((err) => {
          console.log(err);
          ElMessage.success('删除失败');
        });
    }
  });
};
//搜索
const onSubmit = async () => {
  formSearch.page = 1;
  await initData();
};
//重置
const onReset = async () => {
  formSearch.StartTime = getInitTime(7);
  formSearch.EndTime = getInitTime();
  formSearch.CityCode = '';
  formSearch.venues = '';
  formSearch.ActivityCode = '';
  formSearch.MatchName = '';
  formSearch.page = 1;
  await initData();
};
//分页
const handleCurrentChange = async (val) => {
  formSearch.page = val;
  await initData();
};
</script>

<style lang="scss" scoped>
.venues {
  margin: 14px 15px 14px;
  .venues-header {
    .drug-head-contatiner-title2 {
      font-size: 18px;
      font-weight: bold;
      color: #333;
      margin-top: 14px;
    }
  }
  .venues-list {
    margin-top: 14px;
  }
}
</style>
